/**
 * @description 待办事项
 * @date 2022-03-17
 */
const Router = require('koa-router')
const categoryRouter = new Router()

const category = require('../models/category')
const todo = require('../models/todo')

const { Op } = require('sequelize')
const { toJSON, httpHandler } = require('../utils/global')
const {
  TODO_CATEGORY_ALL,
  TODO_CATEGORY_FINISHED,
} = require('../utils/globalParams')

// 获取列表
categoryRouter.get('/list', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const data = await category.findAll()
    let res = toJSON(data, null, 2)

    return res
  })
})

// 获取列表
categoryRouter.get('/listAndNumber', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const todoNumberObj = await getTodoNumberGroupByCategory()
    const data = await category.findAll()
    let res = toJSON(data, null, 2)

    // 增加 '全部' 分类
    res.unshift({
      title: TODO_CATEGORY_ALL,
    })

    res.forEach((v) => {
      // "All"分类的显示单行
      v.title === TODO_CATEGORY_ALL
        ? (v.mode = 'SINGLE_ROW')
        : (v.mode = 'DOUBLE_ROW')
      // 待办数量
      v.number = todoNumberObj?.[v.title] || 0
    })
    return res
  })
})

// 根据分类汇总，获取对应数量
async function getTodoNumberGroupByCategory() {
  return new Promise(async (resolve, reject) => {
    try {
      const unFinishData = await todo.count({
        group: 'category',
        attributes: ['category'],
        where: {
          isFinish: {
            [Op.eq]: '否',
          },
        },
      })

      // res: [{ category: 'Work', count: 3 }, { category: 'Study', count: 2 }]
      let arrayUnFinish = toJSON(unFinishData)
      let res = {}

      // 处理成：{'Work': 3, 'Study': 2 }
      let allCount = arrayUnFinish.reduce((prev, cur) => {
        res[cur.category] = cur.count
        return prev + cur.count
      }, 0)

      // 所有项目求和
      res[TODO_CATEGORY_ALL] = allCount

      const finished = await getFinished()

      Object.assign(res, finished)

      resolve(res)
    } catch (err) {
      reject(new Error(err))
    }
  })
}

// 获取未完成数据对应数量
async function getFinished() {
  return new Promise(async (resolve, reject) => {
    try {
      const finishedCount = await todo.count({
        where: {
          isFinish: {
            [Op.eq]: '是',
          },
        },
      })

      let res = {}

      // 已完成的项目求和，处理成格式如：{'Finished': 3 }
      res[TODO_CATEGORY_FINISHED] = finishedCount

      resolve(res)
    } catch (err) {
      reject(new Error(err))
    }
  })
}

module.exports = categoryRouter
